package com.xexun.gpstracker.my;


import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.*;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.media.Image;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.*;
import com.xexun.gpstracker.channel.R;


import java.util.*;

import static com.xexun.gpstracker.channel.R.color.yellow;

/**
 * 搜索界面
 */

public class RadarActivity extends Activity implements View.OnClickListener{

    private Button backBtn,scanBtn;
    private BluetoothAdapter mBluetoothAdapter;
    private Handler mHandler;
    private TextView monitorTV;
    // private BluetoothAdapter mBtAdapter;

    public static final String TAG = "DeviceListActivity";

    List<BluetoothDevice> deviceList;
    List<ShowDevice> deviceNameList = new ArrayList<ShowDevice>();
    List<ShowDevice> warningdevice = new ArrayList<ShowDevice>();

    private ServiceConnection onService = null;
    Map<String, Integer> devRssiValues;
    private static final long SCAN_PERIOD = 10000; //10 seconds

    private boolean mScanning;

    private ImageView bullIV; //牛
    private TextView  bullTV;
    private LinearLayout bullLayout;

    private RelativeLayout mRlImg;

    private BTDeviceAdapter deviceAdapter;


    private static final  String  BTNAME = "XEXUN_DEVICE_";
//    private static final  String  BTNAME = "";


    private boolean startMonitor  = false;
    private int startMonitorTime = 0;
    private  static  int WARNINGTIME = 2;
    private  static  int SCANTIME = 7;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radar);

        initView();

//      initSearch();

        Search();


    }


    private void initView(){

        mRlImg = (RelativeLayout) findViewById(R.id.rl_img);

        backBtn = (Button) findViewById(R.id.backBtn);
        backBtn.setOnClickListener(this);

        monitorTV = (TextView) findViewById(R.id.monitorTV);

        scanBtn = (Button) findViewById(R.id.scanBtn);
        scanBtn.setOnClickListener(this);
    }



    private void Search(){

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 注册用以接收到已搜索到的蓝牙设备的receiver
        IntentFilter mFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, mFilter);
        // 注册搜索完时的receiver
        mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, mFilter);

        populateList();


    }


    private void startSearch(){

            // 如果正在搜索，就先取消搜索
            if (mBluetoothAdapter.isDiscovering()) {
                mBluetoothAdapter.cancelDiscovery();
            }
            // 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回
            mBluetoothAdapter.startDiscovery();

    }





    //设置控件位置
    public void setposition (View view)
    {

        Random random=new Random();


        WindowManager wm = this.getWindowManager();

        //获取屏幕尺寸
        int width = wm.getDefaultDisplay().getWidth() - 400;
        int height = wm.getDefaultDisplay().getHeight() - 500;

        int left = random.nextInt(width)  + 150;
        int top =  random.nextInt(height) + 150;



        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
        params.setMargins(left, top, 0, 0);// 通过自定义坐标来放置你的控件
        view.setLayoutParams(params);
    }








    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void initSearch(){
        mHandler = new Handler();
        // Use this check to determine whether BLE is supported on the device.  Then you can
        // selectively disable BLE-related features.
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "蓝牙电量过低，不可用", Toast.LENGTH_SHORT).show();
            finish();
        }

        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
        // BluetoothAdapter through BluetoothManager.
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "蓝牙电量过低，不可用", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        populateList();

    }

   private  ListView newDevicesListView = null;

    private void populateList() {
        /* Initialize device list container */
        Log.d(TAG, "populateList");
        deviceList = new ArrayList<BluetoothDevice>();
        deviceAdapter = new BTDeviceAdapter(this, deviceList);
        devRssiValues = new HashMap<String, Integer>();

       newDevicesListView = (ListView) findViewById(R.id.new_devices);
        newDevicesListView.setAdapter(deviceAdapter);
        newDevicesListView.setOnItemClickListener(mDeviceClickListener);
//        newDevicesListView.setEnabled(false);


        startSearch();
//        scanLeDevice(true);

    }


    private ShowDevice currentDevice;

    private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


            ViewGroup vg = (ViewGroup)view;

            TextView scanTV = (TextView) vg.findViewById(R.id.scanTV);

            if(scanTV.getText().toString().equals("监控")){

                reset();

                scanTV.setText("监控中");


                BluetoothDevice device = deviceList.get(position);

                setScanDevice(device);
            }



//          showDialog_Layout(RadarActivity.this,device.getAddress());





        }
    };




    private void setScanDevice(BluetoothDevice device){

        currentDevice = new ShowDevice();

        currentDevice.setAddress(device.getAddress());
        currentDevice.setName(device.getName());
        deviceNameList.add(currentDevice);
        deviceAdapter.notifyDataSetChanged();


        handler.removeCallbacks(task);

        warningdevice.clear();
        startMonitor  = true;
        warningdevice.addAll(deviceNameList);
        handler.post(task);

    }



    //显示基于Layout的AlertDialog
    private void showDialog_Layout(Context context,String address) {
            LayoutInflater inflater = LayoutInflater.from(this);
             final View textEntryView = inflater.inflate(
                            R.layout.dialoglayout, null);
             final EditText edtInput=(EditText)textEntryView.findViewById(R.id.edtInput);
             final AlertDialog.Builder builder = new AlertDialog.Builder(context);
             builder.setCancelable(false);
              builder.setIcon(R.drawable.radar_notification);
              builder.setTitle("绑定姓名:"+address);
               builder.setView(textEntryView);
                builder.setPositiveButton("确认",
                            new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int whichButton) {

                       currentDevice.setName(edtInput.getText().toString());
                        deviceNameList.add(currentDevice);

                       deviceAdapter.notifyDataSetChanged();

                                   }
                });
              builder.setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                                  setTitle("");
                               }
               });
             builder.show();
          }



    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void scanLeDevice(final boolean enable) {
        final Button cancelButton = (Button) findViewById(R.id.btn_cancel);
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
                @Override
                public void run() {
                    mScanning = false;
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);

                }
            }, SCAN_PERIOD);

            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }

    }



    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

                @Override
                public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    addDevice(device,rssi);
                                }
                            });

                        }
                    });
                }
            };


       private boolean SHOW = false;


    private void addDevice(BluetoothDevice device, int rssi) {
        boolean deviceFound = false;

        for (BluetoothDevice listDev : deviceList) {
            if (listDev.getAddress().equals(device.getAddress())) {
                deviceFound = true;
                break;
            }
        }


        devRssiValues.put(device.getAddress(), rssi);

        if (!deviceFound &&device.getName() != null&& device.getName().equals(BTNAME) && !startMonitor ) {

            deviceList.add(device);

            deviceAdapter.notifyDataSetChanged();

//            Toast.makeText(this,device.getAddress(),Toast.LENGTH_LONG).show();

        }

    }


    private boolean STARTWARNING = false;

    private Handler handler = new Handler();

    private int WARNING = 0;

    private Vibrator vibrator;
    private MediaPlayer mediaPlayer;

    private Runnable task =new Runnable() {
        public void run() {
            // TODOAuto-generated method stub
            handler.postDelayed(this,SCANTIME*1000);//设置延迟时间，此处是3秒
            //需要执行的代码

//            Toast.makeText(RadarActivity.this,"扫描次数:"+startMonitorTime+"未检测到个数:"+warningdevice.size(),Toast.LENGTH_SHORT).show();


            if (startMonitorTime >= WARNINGTIME && warningdevice.size() > 0 ){

                STARTWARNING  = true ;

                /**
                 * 报警
                 */

                deviceAdapter.notifyDataSetChanged();

             String name = "";

             for (ShowDevice device : warningdevice){

                 name+=device.getName();

             }


//             Toast.makeText(RadarActivity.this,"警报！:"+name+"不在监控范围",Toast.LENGTH_LONG).show();
                vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
                long [] pattern = {100,400,100,400};   // 停止 开启 停止 开启
                vibrator.vibrate(pattern,2);           //重复两次上面的pattern 如果只想震动一次，index设为-1

                if (null == mediaPlayer) {
                    mediaPlayer = MediaPlayer.create(RadarActivity.this, R.raw.alarm);
                    mediaPlayer.setVolume(1.0f, 1.0f);
                    mediaPlayer.setLooping(true);
                }
                mediaPlayer.start();



                warningdevice.clear();
                warningdevice.addAll(deviceNameList);

            }else if(startMonitorTime >= WARNINGTIME){
                reset ();
                deviceAdapter.notifyDataSetChanged();
            }


            startMonitorTime++;


/**
 * 刷新界面
 */
//            if(deviceList != null && deviceList.size() > 0){
//                deviceList.clear();
//                deviceAdapter.notifyDataSetChanged();
//            }

//            scanLeDevice(true);
            startSearch();
        }
    };


    private void reset (){
        STARTWARNING = false;
        startMonitorTime = 0;
        warningdevice.clear();
        warningdevice.addAll(deviceNameList);
        if(null!=vibrator){
            vibrator.cancel();
        }
        if (null != mediaPlayer) {
            mediaPlayer.pause();
        }
    }

    private boolean scan = false;

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case  R.id.backBtn:
                this.finish();
                break;
            case  R.id.scanBtn:
//                handler.postDelayed(task,5000);//延迟调用

                if(!scan){
                    scan = true;
                    scanBtn.setText("完成");
                    monitorTV.setText("请编辑设备名");
                    monitorTV.setVisibility(View.VISIBLE);
                    newDevicesListView.setEnabled(true);
                    deviceAdapter.notifyDataSetChanged();
                }else{
                    if(deviceNameList.size()==0){
                        Toast.makeText(this,"请编辑设备名",Toast.LENGTH_SHORT).show();
                        return;
                    }

                    scan = false;
                    scanBtn.setVisibility(View.GONE);
                    monitorTV.setText("正在监控");
                    startMonitor  = true;
                    warningdevice.addAll(deviceNameList);
                    handler.post(task);
                    newDevicesListView.setEnabled(false);
                }



                break;
            default:
                break;

        }


    }


    @Override
    public void onStart() {
        super.onStart();

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onStop() {
        super.onStop();
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
        handler.removeCallbacks(task);
        if(null!=vibrator){
            vibrator.cancel();
        }
        if (null != mediaPlayer) {
            mediaPlayer.stop();
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
        //解除注册
        unregisterReceiver(mReceiver);
    }

    protected void onPause() {
        super.onPause();
        scanLeDevice(false);
    }

    class BTDeviceAdapter extends BaseAdapter {
        Context context;
        List<BluetoothDevice> devices;
        LayoutInflater inflater;

        public BTDeviceAdapter(Context context, List<BluetoothDevice> devices) {
            this.context = context;
            inflater = LayoutInflater.from(context);
            this.devices = devices;
        }

        @Override
        public int getCount() {
            return devices.size();
        }

        @Override
        public Object getItem(int position) {
            return devices.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewGroup vg;

            if (convertView != null) {
                vg = (ViewGroup) convertView;
            } else {
                vg = (ViewGroup) inflater.inflate(R.layout.device_element, null);
            }

            BluetoothDevice device = devices.get(position);
            final TextView tvadd = ((TextView) vg.findViewById(R.id.address));
            final TextView tvname = ((TextView) vg.findViewById(R.id.name));
            final TextView tvpaired = (TextView) vg.findViewById(R.id.paired);
            final TextView tvrssi = (TextView) vg.findViewById(R.id.rssi);
            final ImageView iv = (ImageView) vg.findViewById(R.id.iv);
            final TextView scanTV = (TextView) vg.findViewById(R.id.scanTV);

//            tvrssi.setVisibility(View.VISIBLE);
//            byte rssival = (byte) devRssiValues.get(device.getAddress()).intValue();
//            if (rssival != 0) {
//                tvrssi.setText("Rssi = " + String.valueOf(rssival));
//            }

            tvname.setText(device.getName());


//            iv.setVisibility(scan ? View.VISIBLE : View.GONE);

//            if(deviceNameList.size() > 0 ){
//            for (ShowDevice showdevice : deviceNameList) {
//
//                if (device.getAddress().equals(showdevice.getAddress())){
//
//                    tvname.setText(showdevice.getName());
//
//
//                }
//            }
//
//            }





                for(ShowDevice showdevice : deviceNameList){
                    if(device.getAddress().equals(showdevice.getAddress())){
                        scanTV.setTextColor(Color.WHITE);
                        scanTV.setText("监控中");
                    }
                }




            if(STARTWARNING){

            for(ShowDevice showdevice : warningdevice){
                if(device.getAddress().equals(showdevice.getAddress())){
                    scanTV.setTextColor(Color.YELLOW);
                    scanTV.setText("报警");
                }
            }

            }





            tvadd.setText(device.getAddress());
            if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                Log.i(TAG, "device::"+device.getName());
                tvname.setTextColor(Color.WHITE);
                tvadd.setTextColor(Color.WHITE);
                tvpaired.setTextColor(Color.GRAY);
                tvpaired.setVisibility(View.VISIBLE);
                tvrssi.setVisibility(View.VISIBLE);
                tvrssi.setTextColor(Color.WHITE);

            } else {
                tvname.setTextColor(Color.WHITE);
                tvadd.setTextColor(Color.WHITE);
                tvpaired.setVisibility(View.GONE);
                tvrssi.setVisibility(View.VISIBLE);
                tvrssi.setTextColor(Color.WHITE);
            }
            return vg;
        }
    }
    private void showMessage(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }


    /**
     * 蓝牙搜索
     */
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            String action = intent.getAction();
            // 获得已经搜索到的蓝牙设备
            if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                if (device.getName() != null&& device.getName().contains(BTNAME)&& !startMonitor) {

//                if (device.getName() != null) {

                    deviceList.add(device);

                    deviceAdapter.notifyDataSetChanged();
                }

                    if(startMonitor){

                        for (Iterator<ShowDevice> it = warningdevice.iterator(); it.hasNext();) {
                            ShowDevice value = it.next();
                            if (value.getAddress().equals(device.getAddress())) {
                                it.remove();  // ok
                            }
                        }

                }


                // 搜索完成
            } else if (action
                    .equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                setProgressBarIndeterminateVisibility(false);

            }
        }
    };
}
